# -*- coding: utf-8 -*-
import base64
import pickle

from django_redis import get_redis_connection


def merge_cart_cookie_to_redis(request, user, response):
    """
    登录时合并购物车,将cookie中的数据合并到redis中
    如果cookie中的数据和redis中有相同的商品记录,以cookie数据为主，覆盖redis中的数据
    :param request:
    :param user:
    :param response:
    :return:
    """
    # 获取cookie中购物车的数据
    cookie_cart = request.COOKIES.get("cart")
    if not cookie_cart:
        return response
    # 解析cookie
    cookie_cart_dict = pickle.loads(base64.b64decode(cookie_cart.encode()))
    # 获取redis中购物车数据(hash)
    redis_conn = get_redis_connection("cart")
    redis_cart = redis_conn.hgetall("cart_%s" % user.id)

    # 用来存储redis最终保存的商品数量信息的hash数据
    cart = {}
    for sku_id, count in redis_cart.items():
        cart[int(sku_id)] = int(count)
    # 用来记录redis最终操作是,需要勾选的sku_id
    redis_cart_selected_add = []
    # 用来记录redis最终操作时,需要取消勾选的sku_id
    redis_cart_selected_remove = []

    for sku_id, count_selected_dict in cookie_cart_dict.items():
        cart[int(sku_id)] = count_selected_dict["count"]

        # 处理商品的勾选状态
        if count_selected_dict['selected']:
            # cookie指明勾选
            redis_cart_selected_add.append(sku_id)
        else:
            # cookie指明不勾选
            redis_cart_selected_remove.append(sku_id)

    if cart:
        # 执行redis操作
        pl = redis_conn.pipeline()

        # 设置hash类型
        pl.hmset("cart_%s" % user.id, cart)
        # 设置set类型
        if redis_cart_selected_remove:
            pl.srem('cart_selected_%s' % user.id, *redis_cart_selected_remove)

        if redis_cart_selected_add:
            pl.sadd('cart_selected_%s' % user.id, *redis_cart_selected_add)
        pl.execute()

    # 删除cooike
    response.delete_cookie("cart")
    return response

